/**
 * @program: data_structures_algorithms
 * @description: 用数组模拟栈
 * @author: lld
 * @create: 2020/08/17 16:36
 **/
public class ArrayStackDemo {
    public static void main(String[] args) {
        ArrayStack arrayStack = new ArrayStack(5);
        arrayStack.push(3);
        arrayStack.push(4);
        arrayStack.push(1);
        arrayStack.push(4);
        arrayStack.push(1);
        arrayStack.push(5);

        try {
            arrayStack.pop();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        System.out.println("出栈顺序：");
        arrayStack.list();
    }
}

//定义ArrayStack表示栈
class ArrayStack {
    private int maxSize;
    private int[] stack;
    private int top = -1;

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
//        初始化数组
        stack = new int[this.maxSize];

    }

    //    判断栈满
    public boolean isFull() {
        return top == maxSize - 1;
    }

    //    判断栈空
    public boolean isEmpty() {
        return top == -1;
    }

    //    入栈
    public void push(int value) {
        if (isFull()) {
            System.out.println("栈满");
            return;
        }
        top++;
        stack[top] = value;
    }

    //    出栈
    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈空,无法出栈");
        }
        int value = stack[top];
        top--;
        return value;
    }

    //显示栈的情况[遍历栈]， 遍历时，需要从栈顶开始显示数据
    public void list() {
        if (isEmpty()) {
            System.out.println("栈空,无法出栈");
            return;
        }
        for (int i = top; i >= 0; i--) {
            System.out.println(stack[i]);
        }
    }
}
